import request from '@/utils/request'

const setUser = (profileData) => ({
  type: 'profile/user',
  payload: profileData
})

const setUserProfile = (userProfile) => {
  return {
    type: 'profile/user/profile',
    payload: userProfile
  }
}
const setToken = () => {
  return {
    type: 'logout'
  }
}

/**
 * 获取用户基本信息
 * @returns {(function(*): Promise<void>)|*}
 */
export const getUser = () => {
  return async (dispatch) => {
    const res = await request('/user')
    dispatch(setUser(res))
  }
}

/**
 * 获取用户详细信息
 * @returns {(function(*): Promise<void>)|*}
 */
export const getProfile = () => {
  return async (dispatch) => {
    const res = await request('/user/profile')
    dispatch(setUserProfile(res))
  }
}

/**
 * 编辑个人资料
 * @param type 修改的类型
 * @param value 修改的值
 */
export const editProfile = (type, value) => {
  return async (dispatch) => {
    await request.patch('/user/profile', {
      [type]: value
    })
    dispatch(getProfile())
  }
}

export const updatePhoto = (formData) => {
  return async (dispatch) => {
    await request.patch('/user/photo', formData)
    dispatch(getProfile())
  }
}

/**
 * 退出
 * @returns {(function(*): Promise<void>)|*}
 */
export const logout = () => {
  return async (dispatch) => {
    dispatch(setToken())
  }
}
